<?php
/**
 * Author：晴天 QQ：1186258278
 * Creation：2020/4/22 13:32
 * Filename：Order.php
 * 订单操作类
 */

namespace lib\supply;


use extend\GoodsCart;
use extend\UserConf;
use Medoo\DB\SQL;
use sms\sms_operation;

class Order
{
    private static $User; //用户信息

    /**
     * @param $Gid 商品ID
     * @param $num 下单数量
     * @param $InputData 下单信息
     * 下单参数验证模块
     */
    public static function VerifyBuy($Gid, $num, $InputData, $User = -1)
    {
        global $conf, $times;

        $arr_blacklist = explode(',', $conf['blacklist']);
        foreach ($arr_blacklist as $v) {
            if (strpos(json_encode($InputData), $v) !== false) dies(-1, '下单信息：<font color="red" size="5">' . $v . '</font><br>已被站长设置为下单违禁词！');
        }

        $DB = SQL::DB();
        $Goods = $DB->get('goods', '*', ['gid' => $Gid, 'state' => 1]);
        if (!$Goods) dies(-1, '商品不存在或已下架！');
        $Repertory = $DB->sum('buylog', 'num', ['gid' => $Gid, 'date[>]' => $times]);

        if (!in_array(7, json_decode($Goods['method'], TRUE))) {
            $num = 1;
        }

        if ($num < 1) $num = 1;
        if ((int)$Repertory >= $Goods['quota']) dies(-1, '商品:' . $Goods['name'] . '<br>库存不足,请明日再来或联系客服添加库存！');

        if (((int)$Repertory + $num) >= $Goods['quota']) dies(-1, '商品:' . $Goods['name'] . '<br>库存不足' . ($Repertory + $num) . '份,请减少购买份数！');


        $Pricer = \price::price_uid(($User == false ? -1 : $User['grade']), (float)$Goods['profits'], $Goods['money'], $Goods['custom']);
        $Goods['price'] = $Pricer['price'];
        $Goods['points'] = $Pricer['points'];

        if ($Goods['price'] == 0 || $Goods['points'] == 0) {

            /**
             * 此处只计算免费商品！
             */

            if ($User == -1) dies(-1, '免费商品必须登陆才可领取！');
            $Day = $DB->sum('buylog', 'num', [
                'gid' => $Goods['gid'],
                'uid' => $User['id'],
                'date[>]' => $times,
            ]);

            if ($Day >= (int)$conf['getinreturn']) {
                @$DB->delete('queue', ['uid' => $User['id'], 'gid' => $Goods['gid'], 'type' => 2]);
                dies(-1, '您今日可免费领取次数已达上限,请明天再来或看看其他付费商品,次日0点更新领取额度！,您今日最多可领取' . $conf['getinreturn'] . '次商品哦！');
            }

            $Day = $DB->sum('buylog', 'num', [
                'gid' => $Goods['gid'],
                'date[>]' => $times,
            ]);

            if ($Day >= (int)$conf['getinreturn_all']) {
                @$DB->delete('queue', ['gid' => $Goods['gid'], 'type' => 2]);
                dies(-1, '本站今日可兑换次数已经耗尽,请明天再来或看看其他付费商品,次日0点免费额度！,本站今日提供了' . $conf['getinreturn_all'] . '次商品领取次数！');
            }
        }

        if ($Goods['min'] <> 0 && $Goods['min'] <> '' && $Goods['min'] <> null) {
            $Quc = ($Goods['min'] / $Goods['quantity']);
            if ($num < $Quc && in_array(7, json_decode($Goods['method'], TRUE))) dies(-1, '当前商品最低购买' . $Quc . '份(' . $Goods['min'] . '个)！');
        }

        if ($Goods['max'] <> 0 && $Goods['min'] <> '' && $Goods['max'] <> null) {
            $Quc = ($Goods['max'] / $Goods['quantity']);
            if ($num > $Quc && in_array(7, json_decode($Goods['method'], TRUE))) dies(-1, '当前商品最多购买' . $Quc . '份(' . $Goods['max'] . '个)！');
        }

        if ($Goods['sqid'] == -3) {
            $count_kami = $DB->count('token', ['gid' => $Gid, 'endtime' => null]);
            if ($count_kami < $num) dies(-1, $Goods['name'] . '卡密库存不足,无法购买！');
        }
        $Goods['num'] = $num;
        return $Goods;
    }

    /**
     * @param $DataBuy 下单信息
     * 下单信息处理模块
     * 下单验证，在线付款链接生成，
     */
    public static function Creation($DataBuy, $User, $Queue = false, $Type = 1)
    {
        global $conf, $date, $times;
        self::$User = $User;

        if ($Queue == false) {
            /**
             * 非提交队列订单模式
             */
            if ($User == false && (int)$DataBuy['type'] !== 1) dies(-2, '请先登陆');
            $Goods = self::VerifyBuy($DataBuy['gid'], $DataBuy['num'], $DataBuy['data'], $User);
            $Money = $Goods['money'] * $Goods['num'];
            /**
             * 启用订单队列
             */
            $DataBuy['num'] = $Goods['num'];
            if ($conf['OredeQueue'] == 2 && $DataBuy['Api'] <> 1) {
                GoodsCart::OredeQueue($DataBuy, $Goods, ($User == false ? -1 : $User['id']));
                return true;
            }
        } else $Goods = $Queue['Goods'];
        /**
         * 支付购买商品
         * 运费模板只对在线下单和余额付款开放！
         */

        $DB = SQL::DB();

        if ($Queue == false) {
            if ($Goods['price'] == 0 && $Goods['points'] == 0) {
                $DataBuy['type'] = 4;
            } else {
                if ((int)$DataBuy['type'] > 3 || (int)$DataBuy['type'] < 1) dies(-1, '数据异常！');
            }
        } else $DataBuy['type'] = 5;

        switch ((int)$DataBuy['type']) {
            case 1:
                if (!in_array(1, json_decode($Goods['method'], TRUE))) {
                    dies(-1, '当前商品未开启在线付款购买方式！<br>请使用其他付款方式购买！');
                }

                $Price = $Goods['price'] * $DataBuy['num'];
                if ($Goods['freight'] <> -1) {
                    $Fre = $DB->get('freight', '*', [
                        'id' => $Goods['freight'],
                        'LIMIT' => 1,
                    ]);
                    if ($Fre) {
                        $Price = \price::freight($Fre, $DataBuy['data'], $Price, $DataBuy['num']);
                    }
                }

                if ((float)$Price < 0.01) dies(-1, '付款金额低于0.01请使用其他方式购买,无法在线支付！');

                switch ($DataBuy['mode']) {
                    case 'wxpay':
                    case 'qqpay':
                    case 'alipay':
                        $PayJson = xiaochu_en(json_encode([
                            'type' => $DataBuy['mode'],
                            'uid' => ($User == false ? -1 : $User['id']),
                            'gid' => $DataBuy['gid'],
                            'input' => $DataBuy['data'],
                            'num' => $DataBuy['num']
                        ]));
                        break;
                    default:
                        dies(-1, '未知付款方式！');
                        break;
                }
                dier(['code' => 2, 'msg' => '您付款成功了吗？点击下方继续!', 'url' => is_https(false) . href() . '/other/submit.php?data=' . $PayJson]);
                break;
            case 2:

                if (!in_array(2, json_decode($Goods['method'], TRUE))) {
                    dies(-1, '当前商品未开启余额付款购买方式！<br>请使用其他付款方式购买！');
                }

                if ($Goods['freight'] <> -1) {
                    $Fre = $DB->get('freight', '*', [
                        'id' => $Goods['freight'],
                        'LIMIT' => 1,
                    ]);
                    if ($Fre) {
                        $Price = \price::freight($Fre, $DataBuy['data'], $Goods['price'], $DataBuy['num']);
                    } else $Price = $Goods['price'] * $DataBuy['num'];
                } else $Price = $Goods['price'] * $DataBuy['num'];

                if ($User['money'] < $Price) dies(-1, '余额不足,还差' . ($Price - $User['money']) . '元！');
                if (($User['money'] - $Price) < 0) dies(-1, '余额异常,请充值再购买！');

                $Deduct = $DB->update('user', [
                    'money[-]' => $Price,
                ], [
                    'id' => $User['id'],
                ]);

                if ($Deduct) {
                    userlog('余额购买', '用户[' . $User['id'] . ']在' . $date . '用' . $Price . '元余额购买了商品[' . $Goods['name'] . ']！', $User['id'], $Price);
                    $OrData = self::OrderAwait('余额付款', '余额付款,无支付订单', $User['id'], $DataBuy, $Price, $Money, false, 1);
                    if ($OrData == false) {
                        $Deducts = $DB->update('user', [
                            'money[+]' => $Price,
                        ], [
                            'id' => $User['id'],
                        ]);
                        if ($Deducts) {
                            userlog('购买失败', '用户[' . $User['id'] . ']在' . $date . '用' . $Price . '元余额购买了商品[' . $Goods['name'] . ']，购买失败' . $Price . '元余额已经补款到账户内！', $User['id'], $Price);
                            dies(-1, '订单创建失败,扣款金额已经补回到您的账户内,请重新尝试哦！');
                        } else {
                            userlog('补款失败', '用户[' . $User['id'] . ']在' . $date . '用' . $Price . '元余额购买了商品[' . $Goods['name'] . ']，购买失败' . $Price . '元余额未补款到账户内,请手动补款！', $User['id'], $Price);
                            dies(-1, '订单创建失败,且补款失败,请联系客服补款');
                        }
                    }
                    return self::OrderSubmit($OrData, $Goods);
                } else dies(-1, '支付失败,无法完成扣款,请联系管理员处理！');
                break;
            case 3:
                if (!in_array(3, json_decode($Goods['method'], TRUE))) {
                    dies(-1, '当前商品未开启积分兑换购买方式！<br>请使用其他付款方式购买！');
                }

                $Day = $DB->count('journal', [
                    'name' => ['积分兑换', '免费领取'],
                    'uid' => $User['id'],
                    'date[>]' => $times,
                ]);

                if ($Day >= $conf['getinreturn']) dies(-1, '您今日积分兑换商品次数已达上限,请明天再来或直接付款购买,次日0点更新额度！,您今日最多可兑换' . $conf['getinreturn'] . '次商品哦！');

                $Day = $DB->count('journal', [
                    'name' => ['积分兑换', '免费领取'],
                    'date[>]' => $times,
                ]);
                if ($Day >= $conf['getinreturn_all']) dies(-1, '本站今日积分兑换商品次数已达上限,请明天再来或直接付款购买,次日0点更新额度！,本站今日提供了' . $conf['getinreturn_all'] . '次商品兑换次数！');

                $Price = $Goods['points'] * $DataBuy['num'];

                if ($User['currency'] < $Price) dies(-1, $conf['currency'] . '不足,还差' . ($Price - $User['currency']) . $conf['currency'] . '！');
                if (($User['currency'] - $Price) < 0) dies(-1, $conf['currency'] . '异常！');

                $Deduct = $DB->update('user', [
                    'currency[-]' => $Price,
                ], [
                    'id' => $User['id'],
                ]);

                if ($Deduct) {
                    userlog('积分兑换', '用户[' . $User['id'] . ']在' . $date . '用' . $Price . $conf['currency'] . '兑换了商品[' . $Goods['name'] . ']！', $User['id'], $Price);
                    $OrData = self::OrderAwait('积分兑换', '积分兑换,无支付订单', $User['id'], $DataBuy, $Price, $Money, false, 1);
                    if ($OrData == false) {
                        $Deducts = $DB->update('user', [
                            'currency[+]' => $Price,
                        ], [
                            'id' => $User['id'],
                        ]);
                        if ($Deducts) {
                            userlog('购买失败', '用户[' . $User['id'] . ']在' . $date . '用' . $Price . $conf['currency'] . '兑换了商品[' . $Goods['name'] . ']，购买失败' . $Price . $conf['currency'] . '已经补款到账户内！', $User['id'], $Price);
                            dies(-1, '订单创建失败,' . $conf['currency'] . '已经补回到您的账户内,请重新尝试哦！');
                        } else {
                            userlog('补款失败', '用户[' . $User['id'] . ']在' . $date . '用' . $Price . $conf['currency'] . '兑换了商品[' . $Goods['name'] . ']，购买失败' . $Price . $conf['currency'] . '未补款到账户内,请手动补款！', $User['id'], $Price);
                            dies(-1, '订单创建失败,且补款失败,请联系客服补' . $conf['currency']);
                        }
                    }
                    return self::OrderSubmit($OrData, $Goods);
                } else dies(-1, '兑换失败,无法完成扣款,请联系管理员处理！');
                break;
            case 4:
                if ($User == false) dies(-2, '领取免费商品需要先登陆用户后台哦');

                userlog('免费领取', '用户[' . $User['id'] . ']在' . $date . '免费领取了商品[' . $Goods['name'] . ']！', $User['id'], 0);
                $OrData = self::OrderAwait('免费领取', '免费商品,无支付订单', $User['id'], $DataBuy, 0, $Money);
                if ($OrData == false) dies(-1, '订单创建失败,无法领取此商品！');
                return self::OrderSubmit($OrData, $Goods);
                break;
            case 5:
                $OrData = self::OrderAwait($Queue['payment'], $Queue['trade_no'], $Queue['uid'], $Queue['DataBuy'], $Queue['price'], $Queue['Money'], $Queue['order'], false, $Type);
                if ($OrData == false) dies(-1, '订单创建失败,无法提交！');
                return self::OrderSubmit($OrData, $Goods);
                break;
            default:
                dies(-1, '未知付款方式！');
                break;
        }
    }

    /**
     * @param $OrData 商品订单号！
     * @param $Goods  下单商品信息
     * 订单创建后的执行操作
     */
    public static function OrderSubmit($OrData, $Goods)
    {
        global $conf;
        switch ((int)$Goods['sqid']) {
            case -1:
                /**
                 * 自营商品
                 */
                return self::Autotrophy($OrData, $Goods);
                break;
            case -2:
                /**
                 * API对接商品
                 */

                $Data = Api::Submit($OrData, $Goods);
                if ($Data == false) return $OrData['id'];

                return self::OrderSet($OrData['id'], ($Data['code'] >= 0 ? 1 : $conf['SubmitState']), $Data['msg'], $Data['order'], $Data['money']);
                break;
            case -3:
                /**
                 * 发卡商品
                 */
                $Data = faka::Submit($OrData, $Goods);
                if ($Data['code'] == 1) {
                    return self::OrderSet($OrData['id'], ($Data['code'] == 1 ? 1 : $conf['SubmitState']), $Data['msg'], $Data['order'], 0);
                } else return $OrData['id'];
                break;
            default:
                /**
                 * 对接卡盟
                 */
                $DB = SQL::DB();
                $TypeSupply = $DB->get('shequ', '*', [
                    'id' => $Goods['sqid'],
                ]);
                if (!$TypeSupply) {
                    return self::OrderSet($OrData['id'], $conf['SubmitState'], '请检查编号[' . $Goods['sqid'] . ']的货源是否存在！', -1, 0);
                }

                if (!strstr($TypeSupply['url'], 'http://') && !strstr($TypeSupply['url'], 'https://')) {
                    $TypeSupply['url'] = 'http://' . $TypeSupply['url'] . '/';
                }

                /**
                 * 1玖伍
                 * 2亿乐
                 * 3小储
                 * 4卡易信
                 */
                $Order = $DB->get('order', '*', ['id' => $OrData['id']]);
                switch ((int)$TypeSupply['type']) {
                    case 1:
                        $Data = jiuwu::Submit($Order, $Goods, $TypeSupply);
                        if ($Data == false) return $OrData['id'];
                        return self::OrderSet($OrData['id'], $Data['code'], $Data['msg'], $Data['order'], $Data['money']);
                        break;
                    case 2:
                        $Data = yile::Submit($Order, $Goods, $TypeSupply);
                        if ($Data == false) return $OrData['id'];
                        return self::OrderSet($OrData['id'], $Data['code'], $Data['msg'], $Data['order'], $Data['money']);
                        break;
                    case 3:
                        $Data = xiaochu::Submit($Order, $Goods, $TypeSupply);
                        if ($Data == false) return $OrData['id'];
                        return self::OrderSet($OrData['id'], $Data['code'], $Data['msg'], $Data['order'], $Data['money']);
                        break;
                    case 4:
                        $Data = kayix::Submit($Order, $Goods, $TypeSupply);
                        if ($Data == false) return $OrData['id'];
                        return self::OrderSet($OrData['id'], $Data['code'], $Data['msg'], $Data['order'], $Data['money']);
                        break;
                    default:
                        return self::OrderSet($OrData['id'], 3, '未知类型的货源ID,无法完成下单！', -1, 0);
                        break;
                }
                break;
        }
    }

    /**
     * @param $state 订单状态
     * @param $return 对接返回信息
     * @param int $order_id 货源订单号
     * @param int $user_rmb 货源余额
     * 修改订单状态！写入社区订单号
     */
    public static function OrderSet($id, $state, $return, $order_id = -1, $user_rmb = 0)
    {
        global $conf, $accredit, $dbconfig;
        $DB = SQL::DB();
        $re = $DB->update('order', [
            'state' => $state,
            'return' => $return,
            'order_id' => $order_id,
            'user_rmb' => $user_rmb,
        ], ['id' => $id]);
        if ($re) {
            $Order = $DB->get('order', [
                '[>]goods' => ['gid' => 'gid'],
            ], [
                'order.gid',
                'order.uid',
                'order.price',
                'order.num',
                'order.input',
                'goods.name',
                'order.payment',
                'order.order',
            ], ['id' => $id]);
            if ($Order) {
                /**
                 * 此处$DB用于兼容下方操作方法
                 */
                $DB = new \DB($dbconfig['host'], $dbconfig['user'], $dbconfig['pwd'], $dbconfig['dbname'], $dbconfig['port']);
                if ($Order['uid'] >= 1 && $conf['sms_switch_order'] == 1) {
                    $sms = new sms_operation(href(), $accredit['token'], 3);
                    $sms->user_order_tips($Order['uid'], $Order['order']);
                }
                UserConf::PushMoney($Order['order'], $Order['gid'], (float)$Order['price'], ($Order['payment'] == '积分兑换' ? 2 : 1), $Order['num'], json_decode($Order['input'], TRUE));
                \query::OrderCookie($Order['order']);
                sms_operation::WeixOrder($Order['order'], $Order['name']);
            }
        }
        return $id;
    }

    /**
     * @param $OrData 订单ID+订单号
     * @param $Goods 商品信息
     * 自营商品提交,自营商品需扩展api控制订单
     */
    public static function Autotrophy($OrData, $Goods)
    {
        global $conf;
        return self::OrderSet($OrData['id'], $conf['SubmitState'], '请联系客服查询具体进度!', '-1', '0');
    }


    /**
     * @param $payment 类型
     * @param $Type 判断
     * @param $Uid 用户ID
     * @param $Price 退款金额
     * @param $DataBuy 信息
     * @param $Msg 返回信息
     *
     */
    public static function PriceRefund($payment = false, $Type = false, $Uid = -1, $Price = 0, $DataBuy = [], $Msg = '', $Code = 1)
    {
        global $date;
        $DB = SQL::DB();
        if ($payment == '余额付款' || $payment == '积分兑换' && $Type <> false) {
            /**
             * 执行退款操作
             */
            $Deducts = $DB->update('user', [
                ($payment == '余额付款' ? 'money' : 'currency') . '[+]' => $Price,
            ], [
                'id' => $Uid,
            ]);
            if ($Deducts) {
                userlog('订单退款', '用户[' . $Uid . ']在' . $date . '用' . $Price . ($payment == '余额付款' ? '元余额' : '点积分') . '购买了商品[' . $DataBuy['gid'] . ']，重复扣款' . $Price . ($payment == '余额付款' ? '元余额' : '点积分') . '已经补款到账户内！', $Uid, $Price);
                dies($Code, $Msg);
            } else {
                userlog('退款失败', '用户[' . $Uid . ']在' . $date . '用' . $Price . ($payment == '余额付款' ? '元余额' : '点积分') . '购买了商品[' . $DataBuy['gid'] . ']，重复扣款' . $Price . ($payment == '余额付款' ? '元余额' : '点积分') . '未补款到账户内, 请联系客服手动补款！', $Uid, $Price);
                dies($Code, $Msg);
            }
        }
    }

    /**
     * @param $payment 支付方式
     * @param $trade_no 支付订单
     * @param $Uid 下单用户
     * @param $DataBuy 下单信息
     * @param $Price 商品金额
     * @param $Money 商品成本
     * @param $OrderID 生成指定的商品订单号
     * 创建待处理订单，内置重复提交验证模块
     */
    public static function OrderAwait($payment, $trade_no, $Uid, $DataBuy, $Price, $Money, $OrderID = false, $Type = false, $TypeMsg = 1)
    {
        global $date, $conf;
        $DB = SQL::DB();
        if ($OrderID == false) {
            $OrderNumber = date("YmdHis") . rand(11111, 99999);
        } else $OrderNumber = $OrderID;

        $Flie = ROOT . '/includes/extend/log/Astrict/Order_' . md5(json_encode($DataBuy['data']) . $DataBuy['gid'] . $DataBuy['num']) . '.log';
        if (file_exists($Flie)) {
            $tiem = (float)file_get_contents($Flie);
            if ((time() - $tiem) < $conf['OrderAstrict']) {
                $Orv = $DB->get('order', '*', [
                    'order' => $OrderNumber,
                ]);
                if ($Orv) {
                    $re = $DB->update('queue', [
                        'type' => 1,
                        'endtime' => $date,
                        'remark' => '您的商品已经成功提交到服务器!',
                    ], ['order' => $OrderNumber]);
                    if ($re) {
                        self::PriceRefund($payment, $Type, $Uid, $Price, $DataBuy, '当前订单已经提交到服务器了,请勿重复提交哦!');
                    } else $DB->delete('queue', ['order' => $OrderNumber, 'id[!]' => $re['id']]);
                    self::PriceRefund($payment, $Type, $Uid, $Price, $DataBuy, '当前订单已经提交到服务器了,请勿重复提交哦!');

                    if ($TypeMsg == 2) {
                        show_msg('温馨提示', '商品已经付款成功！', 1, '/?mod=query');
                    } else if ($TypeMsg == 3) {
                        die('success');
                    } else dies(1, '当前订单已经提交到服务器了,请勿重复提交哦!');
                }
                self::PriceRefund($payment, $Type, $Uid, $Price, $DataBuy, '重复下单数据有提交间隔期 <br>请于' . ($conf['OrderAstrict'] - (time() - $tiem)) . '秒后再提交!', -1);

                if ($TypeMsg == 2) {
                    show_msg('温馨提示', '商品已经付款成功！', 1, '/?mod=query');
                } else if ($TypeMsg == 3) {
                    die('success');
                } else dies(-1, '重复下单数据有提交间隔期 <br>请于' . ($conf['OrderAstrict'] - (time() - $tiem)) . '秒后再提交!');
            }
            @file_put_contents($Flie, time());
        } else @file_put_contents($Flie, time());

        $Order = $DB->insert('order', [
            'order' => $OrderNumber,
            'trade_no' => $trade_no,
            'uid' => $Uid,
            'ip' => userip(),
            'input[JSON]' => $DataBuy['data'],
            'state' => 2,
            'num' => $DataBuy['num'],
            'return' => '用户已付款,订单尚未处理！',
            'gid' => $DataBuy['gid'],
            'money' => $Money,
            'payment' => $payment,
            'price' => $Price,
            'addtitm' => $date,
        ]);
        $ID = $DB->id();
        if ($Order) {
            $DB->insert('buylog', [
                'gid' => $DataBuy['gid'],
                'uid' => $Uid,
                'num' => $DataBuy['num'],
                'ip' => userip(),
                'date' => $date,
            ]);
            return [
                'id' => $ID,
                'order' => $OrderNumber,
            ];
        } else return false;
    }


    /**
     * @param $PayOrder 支付订单号
     * @param $Data 支付回调信息
     * @param $Type =2则返回show_msg信息
     *
     */
    public static function SubmitPay($Queue, $Data, $Type = 1)
    {
        global $date;
        $DB = SQL::DB();
        $Goods = $DB->get('goods', '*', ['gid' => $Queue['gid']]);
        if (!$Goods) return ['code' => -1, 'msg' => '此订单商品不存在,无法提交至服务器,请联系管理员处理！'];

        $Goods['price'] = $Queue['money'];
        $Goods['points'] = $Queue['money'];
        $Goods['num'] = $Queue['num'];

        $Queue['Money'] = $Goods['money'] * $Queue['num'];
        $Queue['Goods'] = $Goods;
        $Queue['DataBuy'] = [
            'gid' => $Goods['gid'],
            'num' => $Queue['num'],
            'data' => json_decode($Queue['input'], TRUE),
        ];

        $Queue['price'] = $Queue['money'];
        $Queue['payment'] = $Queue['type'];
        $Queue['trade_no'] = $Data['trade_no'];
        $Queue['order'] = date("YmdHis") . rand(11111, 99999);
        $ID = self::Creation(false, ($Queue['uid'] == -1 ? false : $Queue['uid']), $Queue, $Type);
        if ($ID <> false) {
            $re = $DB->update('pay', [
                'state' => 1,
                'trade_no' => $Data['trade_no'],
                'endtime' => $date,
            ], ['id' => $Queue['id']]);

            if ($re) {
                userlog('在线购买', '用户[' . $Queue['uid'] . ']在' . $date . '在线支付了' . $Queue['money'] . '元购买了商品[' . $Goods['name'] . ']！', $Queue['uid'], $Queue['money']);
                return [
                    'code' => 1,
                    'msg' => '商品[' . $Goods['name'] . ']购买成功!',
                    'id' => $ID
                ];
            } else return [
                'code' => -1,
                'msg' => '订单提交失败,无法提交到服务器!',
            ];
        } else return [
            'code' => -1,
            'msg' => '订单提交失败,无法提交到服务器,商品对接发生异常!',
        ];
    }

    /**
     * @param bool $ID 订单ID
     * @param int $num 批量提交数量
     * 提交订单队列内容！
     */
    public static function SubmitOrderQueue($ID = false, $num = 2)
    {
        $DB = SQL::DB();
        if ($ID == false) {
            $QueueArr = $DB->select('queue', ['id'], [
                'type' => 2,
                'ORDER' => 'id',
                'LIMIT' => $num
            ]);

            if (!$QueueArr) return ['code' => 1, 'msg' => '无需监控,队列内无订单!'];
            $i = 0;
            $e = 0;
            foreach ($QueueArr as $value) {
                if (self::OrderQueueId($value['id'])['code'] == -2) {
                    ++$e;
                } else {
                    ++$i;
                }
            }
            return [
                'code' => 1,
                'msg' => '本次共需提交' . $num . '条订单,成功' . $i . '条，失败' . $e . '条！',
            ];
        } else {
            dier(self::OrderQueueId($ID));
        }
    }

    /**
     * @param $ID 订单ID
     * 提交单个订单商品到订单队列！
     */
    public static function OrderQueueId($ID)
    {
        global $date;
        $DB = SQL::DB();
        $Queue = $DB->query('SELECT * FROM `pre_queue` WHERE `id` = :ID AND `type` = 2 LIMIT 1 FOR UPDATE ', [
            ':ID' => $ID
        ])->fetchAll()[0];

        if (empty($Queue['order'])) return ['code' => -1, 'msg' => '订单不存在或已经提交至服务器！'];

        $Order = $DB->query("SELECT * FROM `pre_order` WHERE `order` = ':order' LIMIT 1 FOR UPDATE", [
            ':order' => $Queue['order']
        ])->fetchAll()[0];

        if (empty($Order['order'])) {
            $Goods = $DB->get('goods', '*', ['gid' => $Queue['gid']]);
            if (!$Goods) return ['code' => -1, 'msg' => '此订单商品不存在,无法提交至服务器,请联系管理员处理！'];
            $User = $DB->get('user', '*', ['id' => $Queue['uid']]);
            if (!$User) {
                $User = false;
            }

            /**
             * 提交队列订单！
             * 生成指定订单号商品
             */

            $Goods['price'] = $Queue['price'];
            $Goods['points'] = $Queue['price'];
            $Goods['num'] = $Queue['num'];

            $Queue['Money'] = $Goods['money'] * $Queue['num'];
            $Queue['Goods'] = $Goods;
            $Queue['DataBuy'] = [
                'gid' => $Goods['gid'],
                'num' => $Queue['num'],
                'data' => json_decode($Queue['input'], TRUE),
            ];

            self::VerifyBuy((int)$Queue['Goods']['gid'], (int)$Queue['Goods']['num'], $Queue['DataBuy']['data'], ($User == false ? -1 : $User));

            $Data = self::Creation(false, $User, $Queue);

            if ($Data <> false) {
                $re = $DB->update('queue', [
                    'type' => 1,
                    'endtime' => $date,
                    'remark' => '您的商品：' . $Goods['name'] . '订单已经成功提交到服务器!',
                ], ['id' => $ID]);

                if ($re) {
                    return [
                        'code' => 1,
                        'msg' => '订单已经成功提交到了服务器',
                        'id' => $ID
                    ];

                } else return [
                    'code' => -1,
                    'msg' => '队列订单状态修改失败,无需重复提交,已经提交到服务器了!',
                ];

            } else return [
                'code' => -2,
                'msg' => '订单提交失败!',
            ];

        } else {
            $re = $DB->update('queue', [
                'type' => 1,
                'endtime' => $date,
                'remark' => '您已经手动提交到了服务器!',
            ], ['id' => $ID]);
            if ($re) {
                return ['code' => -1, 'msg' => '订单已经提交到服务器,无法重复提交！'];
            } else return ['code' => -1, 'msg' => '订单状态修改失败,此订单已经被提交到了服务器,无需重复提交！'];
        }
    }

    /**
     * @param $ID 订单id
     * 查询订单进度！
     */
    public static function Query($ID, $Uid = false)
    {
        $Data = [];
        $DB = SQL::DB();
        if ($Uid == false) {
            $Order = $DB->get('order', '*', [
                'id' => $ID,
            ]);
        } else {
            /**
             * Api查单时只可以通过订单号查询！
             */
            $Order = $DB->get('order', '*', [
                'order' => $ID,
                'uid' => $Uid,
            ]);
        }


        if (!$Order) dies(-1, '订单不存在！');

        $Goods = $DB->get('goods', '*', [
            'gid' => $Order['gid'],
        ]);

        if (!$Goods) dies(-1, '商品不存在！');

        if ($Goods['sqid'] > 0 && $Order['order_id'] <> -1 && $Order['order_id'] <> '' && $Order['order_id'] <> 1) {
            $TypeSupply = $DB->get('shequ', '*', [
                'id' => $Goods['sqid'],
            ]);
            if ($TypeSupply) {
                //1,玖伍,2亿乐,3同系统,4卡易信
                switch ((int)$TypeSupply['type']) {
                    case 1:
                        $Data = jiuwu::Query($Order['order_id'], $TypeSupply);
                        break;
                    case 2:
                        $Data = yile::Query($Order['order_id'], $TypeSupply);
                        break;
                    case 3:
                        $Data = xiaochu::Query($Order['order_id'], $TypeSupply);
                        break;
                    case 4:
                        $Data = kayix::Query($Order['order_id'], $TypeSupply);
                        break;
                }
            }
        }

        $InputArr = json_decode($Order['input'], true);
        $i = 0;

        $GoodsInputArr = explode('|', $Goods['value']);
        $GoodsInput = [];
        foreach ($InputArr as $value) {
            if (empty($GoodsInputArr[$i])) $GoodsInputArr[$i] = '输入框' . ($i + 1);
            if (strstr($GoodsInputArr[$i], '{') && strstr($GoodsInputArr[$i], '}')) {
                $GoodsInput[] = explode('{', $GoodsInputArr[$i])[0] . ':' . $value;
            } else $GoodsInput[] = $GoodsInputArr[$i] . ':' . $value;
            ++$i;
        }

        $GetToken = $DB->select('token', ['token'], ['order' => $Order['order']]);
        if (count($GetToken) <> 0) {
            $TokenArr = [];
            foreach ($GetToken as $value) {
                $TokenArr[] = $value['token'];
            }
        } else {
            $TokenArr = -1;
        }

        $Data = array_merge($Data, [
            'gid' => $Goods['gid'],
            'order' => $Order['order'],
            'order_id' => $Order['order_id'],
            'ip' => $Order['ip'],
            'name' => $Goods['name'],
            'price' => $Order['price'],
            'addtiem' => $Order['addtitm'],
            'input' => $GoodsInput,
            'state' => self::OrderState((int)$Order['state']),
            'docs' => htmlspecialchars_decode($Goods['docs']),
            'type' => $Order['payment'],
            'remark' => $Order['remark'],
            'num' => ($Order['num'] * $Goods['quantity']),
            'url' => '/?cid=' . $Goods['cid'] . '&gid=' . $Goods['gid'],
            'token_arr' => $TokenArr
        ]);

        return [
            'code' => 1,
            'msg' => '订单查询成功',
            'data' => $Data
        ];
    }

    /**
     * @param $ID 订单补单！
     * 目前只有补单功能独立于订单创建外,其他均要验证订单！
     */
    public static function Retry($ID)
    {
        $DB = SQL::DB();
        $Order = $DB->get('order', '*', [
            'id' => $ID,
        ]);
        if ($Order['satte'] == 1) dies(-1, '已完成订单无法补单！');
        $Data = [
            'id' => $ID,
            'order' => $Order['order'],
        ];
        $Goods = $DB->get('goods', '*', [
            'gid' => $Order['gid'],
        ]);

        if (!$Goods) dies(-1, '商品不存在,无法补单！');
        $Re = self::OrderSubmit($Data, $Goods);
        if ($Re == false) dies(-1, '补单失败！');
        $return = $Order['return'];
        $Order = $DB->get('order', ['return'], [
            'id' => $ID,
        ]);
        if ($Order['return'] == $return) dies(-1, '补单失败:' . $Order['return']);
        dies(1, '补单返回结果:<br>' . $Order['return']);
    }


    /**
     * @param $Id 类型参数
     * @param $Type 类型
     * 返回状态
     */
    private static function OrderState($Id)
    {
        switch ($Id) {
            case 1:
                return '已完成';
                break;
            case 2:
                return '待处理';
                break;
            case 3:
                return '异常';
                break;
            case 4:
                return '正在处理';
                break;
            case 5:
                return '已退款';
                break;
            case 6:
                return '售后维权';
                break;
            case 7:
                return '已评价';
                break;
            default:
                return '未知状态';
                break;
        }
    }
}